import arcpy
import arcpy.mapping as mp
import pandas as pd
import sys
import shutil
import os
reload(sys)
sys.setdefaultencoding('utf-8')



split_csv_path = r"E:\tutu\cut\hach" #切片csv路径（2500个）
area_csv_path = r"E:\tutu\cut\area"  #导出csv路径，每次运行都会被清空，不要放重要的文件



if not os.path.exists(area_csv_path):
    os.mkdir(area_csv_path)
else:
    shutil.rmtree(area_csv_path)
    os.mkdir(area_csv_path)

def got_rect_locations():
    mxd = mp.MapDocument('CURRENT')
    lsd = mp.ListDataFrames(mxd)
    data_in_layout = True
    for df in lsd :
        if not data_in_layout:
            break
        for layer in mp.ListLayers(df):
            if layer.name == "Converted_Graphics":
                data_in_layout = False
                Converted_Graphics = layer
                break

    if not data_in_layout:
        with arcpy.da.SearchCursor(Converted_Graphics , ["OID@", "SHAPE@"]) as cursor:
            rect_locations = []
            for row in cursor:
                point_list = list(set([(point.X,point.Y) for point in row[1][0]]))
                left,bottom,right,top = min([i[0] for i in point_list]), min([i[1] for i in point_list]),max([i[0] for i in point_list]), max([i[1] for i in point_list])
                rect_locations.append ((left,bottom,right,top))
    else:
        relative_locations = []
        rect_locations = []
        mimor_df = min(arcpy.mapping.ListLayoutElements(mxd, "DATAFRAME_ELEMENT"),key = lambda x:x.elementWidth)
        left,bottom,right,top = mimor_df.elementPositionX,mimor_df.elementPositionY,mimor_df.elementPositionX + mimor_df.elementWidth,mimor_df.elementPositionY + mimor_df.elementHeight

        for elm in arcpy.mapping.ListLayoutElements(mxd, "GRAPHIC_ELEMENT"): 
            if right-elm.elementWidth > elm.elementPositionX > left and top -  elm.elementHeight > elm.elementPositionY >bottom :
                relative_locations.append((elm.elementPositionX,elm.elementPositionY,elm.elementPositionX+elm.elementWidth,elm.elementPositionY+elm.elementHeight))
        minX,minY,maxX,maxY =  mimor_df.extent.XMin,mimor_df.extent.YMin,mimor_df.extent.XMax,mimor_df.extent.YMax
        for i in relative_locations:
            absolute_minX = ((i[0] - left)/(right-left))*(maxX-minX)+minX
            absolute_maxX = ((i[2] - left)/(right-left))*(maxX-minX)+minX
            absolute_minY = ((i[1] - bottom)/(top-bottom))*(maxY-minY)+minY   
            absolute_maxY = ((i[3] - bottom)/(top-bottom))*(maxY-minY)+minY
            rect_locations .append((absolute_minX,absolute_minY,absolute_maxX,absolute_maxY))
    return rect_locations    

def release_rect(rect_locations,polygonName):
    k = [[0 for i in range(len(rect_locations))] for i in range(len(rect_locations))]
    
    with arcpy.da.SearchCursor(polygonName, ["SHAPE@","区域"]) as cursor:
        for row in cursor:
            maxX = max([i.X for i in row[0][0] if i ])
            maxY = max([i.Y for i in row[0][0] if i ])
            minX = min([i.X for i in row[0][0] if i ])
            minY = min([i.Y for i in row[0][0] if i ])
    
            for index,rect in enumerate(rect_locations):
                if minX > rect[0] and maxX < rect[2] and minY >rect[1] and maxY < rect[3]:
                    assert (int(row[1])-1 < len(k[index])),"图斑地域标错了"
                    k[index][int(row[1])-1] += 1    
            
    count = 0
    return_dict = {}
    for i in k:
        return_dict[ i.index(max(i))+1] = rect_locations[count]
        count += 1
    return return_dict         


def init():
    mxd = mp.MapDocument('CURRENT')
    lsd = mp.ListDataFrames(mxd)
    default_name = ""
    for df in lsd :
        for layer in mp.ListLayers(df):
            if "_图斑" in layer.name:
                assert (not default_name or default_name == layer.name),"有其他图斑图层存在，删掉保证mxd文件中图斑名称唯一"
                default_name = layer.name
    
              
    return_dict= release_rect(got_rect_locations(),default_name)
    
    assert (return_dict.keys()),"没有查到红框，红框在小图数据框内需要切换数据视图，将图形转换为要素"
    
    for key,xy in return_dict.items():
        x_range = (max(0,int((xy[0]+2578398.0)/93481)),min(51,int((xy[2]+2578398.0)/93481)+2))
        y_range = (max(0,int((xy[1]-2367556.5)/80400)),min(51,int((xy[3]-2367556.5)/80400)+2))
        df = pd.DataFrame()
        for i in range(x_range[0],x_range[1]):
            for j in range(y_range[0],y_range[1]):
                df2 = pd.read_csv(split_csv_path +"/%s,%s.csv"%(i,j))
                df2 = df2[( xy [0] < df2.xx) & (xy [1] < df2.yy) &(df2.xx<=xy [2]) &(df2.yy<=xy [3] )]
                df = pd.concat([df,df2])
                
        
        tempr = ['嗯嗯','高山极地','苔原','寒温','中温','暖温','亚热','热']

        tpr = ".".join(str(tempr.index(i)) for i in default_name.split("_")[-2].split("带")[:-1] if i != "交错")
            
        
        df.to_csv(area_csv_path + "/" + default_name.replace("_图斑","") + "----" + str(key) + "----" + tpr + "----.csv")
init()